package com.yangyouli.unity_demo_server.service.impl;

import com.yangyouli.unity_demo_server.annotation.Inject;
import com.yangyouli.unity_demo_server.annotation.Injectable;
import com.yangyouli.unity_demo_server.dao.ExpContrastDao;
import com.yangyouli.unity_demo_server.dao.UserDataDao;
import com.yangyouli.unity_demo_server.entity.ExpContrast;
import com.yangyouli.unity_demo_server.entity.UserData;
import com.yangyouli.unity_demo_server.service.UserDataService;

@Injectable("userDataService")
public class UserDataServiceImpl implements UserDataService{

	@Inject
	UserDataDao userDataDao;
	@Inject
	ExpContrastDao expContrastDao;
	
	@Override
	public int updateStringFieldByUserId (UserData userData) {
		return userDataDao.update(userData);
	}

	@Override
	public int UpdateNumbricFieldByUserId (UserData userData) {
		return userDataDao.updateNumbricField(userData);
	}

	@Override
	public UserData findByUserId (int userId) {
		return userDataDao.findByUserId(userId);
	}

	@Override
	public int addMoney(UserData userData) {
		UserData temp = userDataDao.findByUserId(userData.getUserId());
		temp.setMoney(userData.getMoney() + temp.getMoney());
		return userDataDao.updateNumbricField(temp);
	}

	@Override
	public int addExp(UserData userData) {
		UserData temp = userDataDao.findByUserId(userData.getUserId());
		temp.setExp(userData.getExp() + temp.getExp());
		ExpContrast expContrast = expContrastDao.findByLevel(temp.getLevel());
		while (expContrast != null && temp.getExp() >= expContrast.getNextLevelRequiredExp() && temp.getLevel() != 100) {
			// 升级
			temp.setExp(temp.getExp() - expContrast.getNextLevelRequiredExp());
			temp.setLevel(temp.getLevel() + 1);
			// 为了减少查询次数
			if (temp.getExp() > expContrast.getNextLevelRequiredExp()) {
				expContrast = expContrastDao.findByLevel(temp.getLevel());
			}
		}
		return userDataDao.updateNumbricField(temp);
	}

}
